import Vue from "vue";
import Vuex from "vuex";

// import Cookies from 'js-cookie'
Vue.use(Vuex);

// if (Cookies.get('profile')) {
//     var profile = JSON.parse(Cookies.get('profile'))
// }

export default new Vuex.Store({
    state: {
        musicList: [],
        //播放列表
        playList: [],
        currentIndex: -1,
        //播放页标识：1.歌库页，2.推荐页，3.My页
        page: 0,
        //播放底部，播放标识
        isPlay: false,
        timeArr: [],
        timeArr_clone: [],
        lyricArr: [],
        lyricIndex: -1,
        scrollTop: -92,
        //分页，每次10条数据
        skip: 0,
        newsList: [],
        newsIndex: -1,
        //喜爱歌曲
        musiclikes: [],
        peoplelikes: [],
        login: false,
        username: ""
    },
    // getters: {},
    mutations: {
        //初始化用户名和登录状态
        initLogin(state, params) {
            let {
                username,
                musiclikes,
                peoplelikes
            } = params
            state.login = true;
            console.log(params, "par");
            state.username = username
            state.musiclikes = musiclikes
            state.peoplelikes = peoplelikes
        },
        //清空本地token和初始化登录状态
        removeLogin(state) {
            localStorage.removeItem("token")
            state.login = false
            state.username = ""
            state.musiclikes = []
        },
        //播放单首歌曲
        musicOnePlay(state, music) {
            state.page = 0
            state.playList = []
            state.playList.push(music)
        },
        //改变识别页，并且将播放列表初始化
        changePage(state, data) {
            state.page = data.page;
            if (data.page === 1) {
                state.playList = state.musicList;
            } else if (data.page === 2) {
                //标识页为2的需要传递播放列表
                state.playList = data.list;
            } else {
                console.log("待补充");
            }
        },
        //初始化歌曲列表,播放列表
        initMusicList(state, musicList) {
            for (let i = 0; i < musicList.length; i++) {
                state.musicList.push(musicList[i]);
                state.playList.push(musicList[i]);
            }
            state.skip++;
        },
        //初始化新闻列表
        initNewsList(state, newsList) {
            for (let i = 0; i < newsList.length; i++) {
                state.newsList.push(newsList[i]);
            }
        },
        //播放索引值为index的歌曲
        start(state, index) {
            let audio = document.getElementsByTagName("audio")[0];
            audio.play();
            state.currentIndex = index;
            state.isPlay = true;
        },
        //暂停歌曲
        pause(state) {
            let audio = document.getElementsByTagName("audio")[0];
            audio.pause();
            state.isPlay = false;
        },
        //解析歌词并初始化数据
        parseLyric(state, index) {
            state.scrollTop = -92;
            state.lyricIndex = -1;
            state.timeArr = [];
            state.timeArr_clone = [];
            state.lyricArr = [];
            let lrc = state.playList[index].lyric;
            if (lrc === "") return "";
            //匹配到每一行的数据：[00:00.00]XXXXXX
            let lyrics = lrc.split("\\n");
            let timeReg = /\[(\d*:\d*\.\d*)\]/;
            for (let i = 0; i < lyrics.length; i++) {
                let lrc = lyrics[i].split("]");
                //去除不存在或无歌词的数据
                if (lrc[1] && lrc.length !== 0) {
                    state.lyricArr.push(lrc[1].trim());
                    //取得时间数组：["[00:00.00]",00:00.00]
                    let timeRegExpArr = timeReg.exec(lyrics[i]);
                    let time = timeRegExpArr[1].split(":");
                    //取分钟值
                    let min = Number(time[0]);
                    //取秒值
                    let sec = Number(time[1]);
                    time = min * 60 + sec;
                    state.timeArr.push(time);
                    state.timeArr_clone.push(time);
                }
            }
        },
        //获取当前歌词索引
        getLyricIndex(state) {
            state.timeArr.shift();
            state.lyricIndex++;
            state.scrollTop += 47;
        },
        //点击歌曲进行跳转
        moveTo(state, index) {
            state.scrollTop = -92 + 47 * index;
            state.lyricIndex = index - 1;
            state.timeArr = [];
            let time = state.timeArr_clone;
            document.getElementsByTagName("audio")[0].currentTime =
                time[index] + 0.001;
            for (let i = index; i <= time.length; i++) {
                state.timeArr.push(time[i]);
            }
        },
        newsIndex(state, index) {
            state.newsIndex = index;
        },
        initMusiclikes(state, musics) {
            for (let i = 0; i < musics.length; i++) {
                if (state.musiclikes.includes(musics[i]._id)) {
                    return;
                }
                state.musiclikes.push(musics[i]._id);
            }
        },
        storeMusic(state, _id) {
            state.musiclikes.push(_id);
        },
        storePeople(state, _id) {
            state.peoplelikes.push(_id)
        }
    },
    actions: {
        //通过索引为index的m_id,souce查找url链接，并播放
        async musicInit({
            state,
            commit
        }, index) {
            let m_id = state.playList[index].m_id;
            let source = state.playList[index].source;
            await Vue.prototype
                .$jsonp("http://www.gequdaquan.net/gqss/api.php/", {
                    types: "url",
                    id: m_id,
                    source: source,
                })
                .then((json) => {
                    let audio = document.getElementsByTagName("audio")[0];
                    audio.src = json.url;
                })
                .catch((err) => {
                    console.log(err);
                });
            commit("start", index);
            commit("parseLyric", index);
        },
        //初始化歌曲列表
        //dispatch,commit,state
        async initMusic({
            commit,
            state
        }) {
            await Vue.prototype.$axios
                .get("/web/music/list", {
                    params: {
                        skip: state.skip,
                    },
                })
                .then((res) => {
                    commit("initMusicList", res.data);
                });
        },
        async initNews({
            commit
        }) {
            await Vue.prototype.$axios
                .get("/web/news/list", {
                    params: {
                        skip: 0,
                    },
                })
                .then((res) => {
                    commit("initNewsList", res.data);
                });
        },
        //保存喜爱的歌曲
        async store({
            state,
            commit
        }, _id) {
            commit("storeMusic", _id);
            await Vue.prototype.$axios
                .post("user/music/store", {
                    musiclikes: state.musiclikes,
                })
                .then((res) => {
                    console.log(res.data);
                }).catch(err => {
                    console.log(err);
                })
        },
        async likePeople({
            state,
            commit
        }, _id) {
            commit("storePeople", _id);
            Vue.prototype.$axios
                .post("user/people/store", {
                    peoplelikes: state.peoplelikes,
                })
                .then((data) => {
                    console.log(data);
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        async disLike({
            state,
            commit
        }, id) {
            if (!id) {
                console.log("_id无效");
            } else {
                await Vue.prototype.$axios.delete(`user/music/dislike/${id}`).then((res) => {
                    console.log(res);
                    commit("initMusiclikes", res.data);
                });
            }
        },
        async dislikePeople({}, id) {
            if (!id) {
                console.log("_id无效");
            } else {
                await Vue.prototype.$axios.delete(`user/people/dislike/${id}`)
                    .catch((err) => {
                        console.log(err);
                    });
            }
        },

        //读取用户个人信息
        async readMsg({
            state,
            commit
        }) {
            await Vue.prototype.$axios.get('user/read').then((res) => {
                if (!res) {
                    commit("removeLogin")
                } else if (res.status === 200) {
                    commit("initLogin", res.data)
                }
            }).catch(err => {
                console.log(err);
            })
        },
    },
    // modules: {},
});